package com.young.app.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.young.app.listener.UserExcelListener;
import com.young.app.model.User;
import com.young.app.service.IUser;
import com.young.app.utils.ExcelListenerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author young
 */
@RestController
@RequestMapping(value = "/app")
public class UserController {
    @Autowired
    IUser iUser;

    /**
     * easyExcel Demo
     * 简单理解的easyExcelDemo
     *
     * @return
     */
    @RequestMapping(value = "/uploadUsers", method = RequestMethod.POST)
    public String uploadUsers() {
        // 文件获取方式不是关注点
        String fileName = UserController.class.getResource("/").getPath() + "excel" + File.separator + "UserList.xlsx";
        // read有同名方法，支持读InputStream
        EasyExcel.read(fileName, User.class, new UserExcelListener(iUser)).sheet().doRead();
        return "Done";
    }

    /**
     * easyExcel DemoPlus
     * 使用到Java8新特性的easyExcelDemo
     *
     * @return
     */
    @RequestMapping(value = "/uploadUsersPlus", method = RequestMethod.POST)
    public String uploadUsersPlus() {
        // 文件获取方式不是关注点
        String fileName = UserController.class.getResource("/").getPath() + "excel" + File.separator + "UserList.xlsx";
        AnalysisEventListener<User> userAnalysisEventListener = ExcelListenerUtils.getListener(this.batchInsert(), 1);
        // read有同名方法，支持读InputStream
        EasyExcel.read(fileName, User.class, userAnalysisEventListener).sheet().doRead();
        return "Done";
    }

    /**
     * User元数据处理Consumer
     *
     * @return
     */
    private Consumer<List<User>> batchInsert() {
        return users -> iUser.saveData(users);
    }
}
